//横向项目列表管理员
<template>
  <div class="module_">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='95px' inline autocomplete="off" :model="pageparm" class="search_box">
          <el-form-item label="合同名称">
            <el-input size="medium" clearable v-model="pageparm.name" placeholder="请输入合同名称搜索" />
          </el-form-item>
          <el-form-item label="合同类型">
            <el-select size="medium" v-model="pageparm.contract_type" clearable
              @change='searchChane($event,"contract_type")' placeholder="请选择合同类型">
              <el-option v-for="item in contractType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人姓名">
            <inputSearch ref="search_e" placeholder="请输入负责人姓名搜索" @onChange='searchChane($event,"leader_id")' />
          </el-form-item>
          <el-form-item label="负责人类型">
            <el-select size="medium" v-model="pageparm.leader_type" clearable
              @change='searchChane($event,"leader_type")' placeholder="请选择负责人类型">
              <el-option v-for="item in leaderType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室" v-if="adminShow">
            <inputSearch ref="search_d" type='departments' @onChange='searchChane($event,"departments_id")' />
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="pageparm.start_time" type="daterange" range-separator="至" start-placeholder="日期范围"
              end-placeholder="日期范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'start_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="终止日期">
            <el-date-picker v-model="pageparm.end_time" type="daterange" range-separator="至" start-placeholder="日期范围"
              end-placeholder="日期范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'end_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="审核类型">
            <el-select size="medium" clearable v-model="pageparm.review_type" placeholder="请选择审核状态搜索"
              @change='searchChane($event,"review_type")'>
              <el-option v-for="item in reviewType2" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索"
              @change='searchChane($event,"review_status")'>
              <el-option v-for="item in newReviewStatus" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button class="mr8" size="medium" type="primary" @click="handle(null,{},3)">新增横向项目</el-button>
          <exportExcel :apiFn='Apicontracts' :self='true' :dataFn='dataFn' name='横向项目列表' />
        </template>
      </search>
    </div>
    <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
      v-loading="tableLoading" stripe @sort-change="tableSortChange" @row-click='viewDetails'>
      <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
        :label="item.label + (item.unit || '')" :min-width="item.width" :fixed="i === 0 ? true: false"
        show-overflow-tooltip :sortable="item.noSort?false:'custom'">
        <template slot-scope="scope">
          <template v-if="item.prop === 'departments_id'">
            {{ scope.row.department?scope.row.department.name:'' }}
          </template>
          <template v-else-if="item.prop === 'leader_id'">
            {{ scope.row.leader_info?scope.row.leader_info.name:''}}
          </template>
          <template v-else-if="item.prop === 'complete_id'">
            {{objToStr(scope.row.complete_name)}}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review.review_comment"
              class="c-red">{{scope.row.status}}：{{scope.row.review.review_comment}} </span>
            <span v-else>{{scope.row.status}}</span>
          </template>
          <template v-else-if="item.prop === 'contract_type'">
            {{ echo(scope.row.contract_type,contractType) }}
          </template>
          <template v-else-if="item.prop === 'leader_type'">
            {{ echo(scope.row.leader_type,leaderType) }}
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="195" class-name="operation">
        <div class="flex-justify-end" slot-scope="scope">
          <el-tooltip effect="dark" content="审核" placement="bottom-end" v-show="showExamine(scope.row)">
            <el-button type="primary" @click.stop="examine_btns(scope.row,1)" size="small" icon="el-icon-help" circle>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="合同立项" placement="bottom-end">
            <el-button v-if="scope.row.project" type="success" @click.stop="examine_project(scope.row)" size="small"
              icon="el-icon-help" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="验收" placement="bottom-end">
            <el-button v-if="scope.row.acceptance" type="success" @click.stop="yanShou(scope.row)" size="small"
              icon="el-icon-s-promotion" circle>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改信息" placement="bottom-end">
            <el-button size="small" @click.stop="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button size="small" type="danger" @click.stop="deleteUser(scope.$index, scope.row)"
              icon="el-icon-delete" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="添加项目成员" placement="bottom-end">
            <el-button size="small" type="primary" @click.stop="goUserInfo(scope.row)" icon="el-icon-user" circle>
            </el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <transverseDialog ref="transverseDialog" :editForm="editForm" :dialogTitle='dialogTitle'
      :editHeaderList="editHeaderList" :leaderType='leaderType' :contractType='contractType' />
    <!-- 审核 -->
    <examineChange ref="examine" @submit='examineSubmit' :title="examineTitle" :nowProject='nowProject'>
      <div v-if="examineChangeFlag">
        <div v-if="examineChangeObj.values.length > 0" class="mb8">
          <h2 class="mb4 f-18">基础信息变更：</h2>
          <table class="table_change" border="1" cellspacing="0">
            <tr>
              <th>变更项</th>
              <th>原始值</th>
              <th>新值</th>
            </tr>
            <tr v-for="(v,i) in examineChangeObj.values" :key="i">
              <td>{{v.label}}</td>
              <td>{{v.origin_value || '无'}}</td>
              <td>{{v.change_value || '无'}}</td>
            </tr>
          </table>
        </div>
        <div v-if="Object.keys(examineChangeObj.files).length > 0">
          <h2 class="mb4 f-18">文件变更：</h2>
          <table class="table_change" border="1" cellspacing="0">
            <tr>
              <th>变更项</th>
              <th>原文件</th>
              <th>新文件</th>
            </tr>
            <tr v-for="(v,i) in examineChangeObj.files" :key="i">
              <td>{{upfilesObj[i]}}</td>
              <td>
                <p v-for="item in v.old" :key="item.origin_value">
                  <span class="shou xialine" @click="uploadFiles(item.origin_value,item.file_name)"><i
                      class="iconfont icon-ziyuan"></i>{{item.file_name}}</span>
                </p>
              </td>
              <td>
                <p v-for="item in v.new" :key="item.change_value">
                  <span class="shou xialine" @click="uploadFiles(item.change_value,item.file_name)"><i
                      class="iconfont icon-ziyuan"></i>{{item.file_name}}</span>
                </p>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </examineChange>

    <htdetails :info='details' ref="detail" />

    <!-- 验收报告 -->
    <acceptanceFiles ref="acceptance" @submit="yanShouSubmit" />
  </div>
</template>

<script>
  import {
    Apicontracts,
    ApicontractsDel,
    ApicontractsCheck,
    ApiupLoadFiles,
    ApicontractsChangeValue,
    Apicontractslixiang,
    ApicontractsAccept,
  } from '@/api'
  import {
    reviewStatus,
    leaderType,
    reviewerTypeObj,
    reviewType2
  } from "@/assets/js"
  import {debounce,adminShow,objToStr} from "@/utils/index";
  import {headerList,contractType,dataFn,editForm} from '../js/transverse'
  import htdetails from "../components/htdetails.vue"
  import transverseDialog from '../components/transverseDialog.vue'
  import acceptanceFiles from "../components/acceptanceFiles.vue"

  export default {
    name: 'project_transverse',
    components: {
      htdetails,
      transverseDialog,
      acceptanceFiles
    },
    computed: {
      newReviewStatus(){
        return [...reviewStatus,{value: 3,label: '待立项'},{value: 4,label: '待验收'}]
      },
      editHeaderList() {
        let list = headerList.filter(item => item.prop !== 'review_status')
        return list.sort((a, b) => b.required - a.required)
      },
      headerObj() {
        return headerList.reduce((obj, item) => {
          obj[item.prop] = item.label
          return obj
        }, {})
      }
    },
    data() {
      return {
        objToStr,
        Apicontracts,
        dataFn,
        adminShow: adminShow(),
        // reviewStatus,
        reviewType2,
        leaderType,
        contractType,

        tableData: [],
        editForm, //修改或者查看详情

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        tableLoading: false,

        headerList,

        examine_id: null, //审核id
        examineChangeObj: {},
        examineChangeFlag: false,
        examineTitle: '',
        nowProject: false,
        upfilesObj: {
          1: '申报通知书附件',
          2: '项目批准通知附件',
          3: '项目协议附件',
          4: '项目预算附件',
          5: '结题报告',
          6: '结题证明',
          7: '验收报告'
        },

        details: {
          review: {}
        },

        dialogTitle: '',
        yanShou_id: null,
      }
    },
    activated() {
      this.getList()
    },
    methods: {
      yanShouSubmit(list){
        const formData = new FormData()
        list.forEach(el=>{
          formData.append('files[]', el.raw)
        })
        ApicontractsAccept(formData,this.yanShou_id,{
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
          this.$refs.acceptance.show = false
          this.getList()
        }).finally(()=>{
          this.$refs.acceptance.btnLoading = false
        })
      },
      yanShou(item) {
        this.yanShou_id = item.id
        this.$refs.acceptance.show = true
      },
      examine_project(item) {
        this.nowProject = true
        this.examine_id = item.id
        this.examineChangeFlag = false
        this.examineTitle = '合同立项'
        this.$refs.examine.examineShow = true
      },
      showExamine(val) {
        let flag = false
        if (val.review.review_status === 0 || (val.change_review && val.change_review.review_status === 0)) {
          flag = true
        }
        return flag
      },
      uploadFiles: debounce(function (url, name) {
        ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
        })
      }, 500, true),

      goUserInfo(value) {
        sessionStorage.setItem('transverseName', value.name)
        this.$router.push('/project/transverse_members?id=' + value.id)
      },
      viewDetails(val, ) {
        this.details = val
        this.$refs.detail.showInfo = true
      },
      //审核
      examineSubmit(options) {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        if (options.file) {
          const formData = new FormData()
          formData.append('review_status', options.review_status)
          formData.append('reviewer_id', options.reviewer_id)
          formData.append('review_comment', options.review_comment || '')
          if (options.file.length > 0) {
            options.file.forEach(item => {
              formData.append('file[]', item.raw)
            })
          }
          Apicontractslixiang(formData, this.examine_id, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            this.$message.success('提交成功')
            this.getList()
          }).finally(() => {
            loading.close()
          })
        } else {
          if (this.examineChangeFlag) options.type = 'change'
          options.id = this.examine_id
          ApicontractsCheck(options, options.id).then(res => {
            this.$message.success('提交成功')
            this.getList()
          }).catch(() => {
            this.$message.error('服务器错误，请重新提交');
          }).finally(() => {
            loading.close()
          })
        }
      },
      examine_btns(item, i) {
        this.nowProject = false
        this.examine_id = item.id
        if (item.change_review && item.change_review.review_status === 0) {
          this.examineTitle = reviewerTypeObj[item.change_review.reviewer_type]
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApicontractsChangeValue(item.change_review.id).then(res => {
            this.examineChangeObj = res.data
            this.examineChangeFlag = true
            if (this.examineChangeObj.values.length > 0) {
              this.examineChangeObj.values.forEach(item => {
                item.label = this.headerObj[item.change_column]
              })
            }
            this.$refs.examine.examineShow = true
          }).finally(() => {
            loading.close()
          })
        } else {
          this.examineChangeFlag = false
          this.examineTitle = reviewerTypeObj[item.review.reviewer_type]
          this.$refs.examine.examineShow = true
        }
      },
      echo(i, arr) {
        let label
        for (const item of arr) {
          if (item.value === i) {
            label = item.label
            break;
          }
        }
        return label
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //搜索
      clearSearch() {
        this.$refs.search_e.clear()
        if (this.adminShow) this.$refs.search_d.clear()
      },
      searchChane(i, val) {
        this.pageparm[val] = i
        this.pageparm.page = 1
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.tableLoading = true
        Apicontracts(this.pageparm).then(({
          data,
          page
        }) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handle(index, value, i) {
        for (const key in this.editForm) {
          this.editForm[key] = value[key]
        }
        this.editForm.files = value.files || {}
        this.$refs.transverseDialog.editFormVisible = true
        this.dialogTitle = '新增横向项目'
        if (i == 2) {
          this.dialogTitle = '编辑横向项目'
        }
      },
      deleteUser(index, value) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApicontractsDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }).finally(() => {
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
    },

  }
</script>
<style lang='less' scoped>
  .table_change {
    width: 100%;
    font-size: 16px;
    border-color: #EBEEF5;

    th {
      width: 33%;
    }

    th,
    td {
      padding: 4px;
    }
  }
</style>